<script setup lang="ts">
import {onMounted, ref, watch} from "vue";
import {
  fetchGetTemplate,
  fetchSaveTemplateBaseParameter,
  fetchSaveTemplateBody,
  fetchSaveTemplateRole
} from "@/service/api/template";
import {FormInst, FormItemRule, useMessage} from 'naive-ui'
import {mapNumberToLetter} from "@/utils/common";

const props = defineProps<{
  templateId: number
}>();

const templateData = ref<Api.Entity.Template>({
  id: null,
  name: '',
  company: null,
  flowData: [],
  formData: [],
  tableData: {},
  role: [],
});
const message = useMessage();
const templateId = ref<number>(props.templateId ? Number(props.templateId) : 0);
const excel = ref();
const roles = ref<any[]>([])
const showRoleModal = ref(false);
const showBaseConfigModal = ref(false);
let width = window.innerWidth - 248;
let innerHeight = window.innerHeight;
const headerValues = ref<any[]>([]);
const headerRow = ref<number>(1);
const config = ref<Excel.Config>({
  autoload: false,
  title: "模板设计",
  width: width,
  height: innerHeight - 160,
  lang: 'zh',
  showtoolbar: true,
  showinfobar: false,
  showtoolbarConfig: {
    chart: false,
    numberDecrease: false,
    numberIncrease: false,
  },
  cellRightClickConfig: {
    hideRow: true,
    hideColumn: true,
    chart: false,
  },
  hook: {
    // sheetMouseup: function (cell, position, sheet, moveState, ctx) {
    // rowStartIndex = position.r
    // console.log(position)
    // }

  }
});

const formRef = ref<FormInst | null>(null)
const formRules = ref({
  inputValue: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入 inputValue'
  },
  textareaValue: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入 textareaValue'
  },
  selectValue: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择 selectValue'
  },
  multipleSelectValue: {
    type: 'array',
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择 multipleSelectValue'
  },
  datetimeValue: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请输入 datetimeValue'
  },
  nestedValue: {
    path1: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入 nestedValue.path1'
    },
    path2: {
      required: true,
      trigger: ['blur', 'change'],
      message: '请输入 nestedValue.path2'
    }
  },
  checkboxGroupValue: {
    type: 'array',
    required: true,
    trigger: 'change',
    message: '请选择 checkboxGroupValue'
  },
  radioGroupValue: {
    required: true,
    trigger: 'change',
    message: '请选择 radioGroupValue'
  },
  radioButtonGroupValue: {
    required: true,
    trigger: 'change',
    message: '请选择 radioButtonGroupValue'
  },
  inputNumberValue: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请输入 inputNumberValue'
  },
  timePickerValue: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请输入 timePickerValue'
  },
  sliderValue: {
    validator(rule: FormItemRule, value: number) {
      return value > 50
    },
    trigger: ['blur', 'change'],
    message: 'sliderValue 需要大于 50'
  },
  transferValue: {
    type: 'array',
    required: true,
    trigger: 'change',
    message: '请输入 transferValue'
  }
});

async function getTemplate() {
  if (templateId.value) {
    fetchGetTemplate(templateId.value).then(res => {
        if (res.data) {
          if (res.data.headerRow != null) {
            headerRow.value = res.data.headerRow;
          }
          templateData.value = res.data;
          if (res.data.body.length > 0) {
            config.value.data = res.data.body;
          }
          if (res.data.role != undefined) {
            roles.value = res.data.role;
          }
          if (config.value.data != undefined) {
            for (let s of config.value.data) {
              if (s.config != undefined) {
                s.config.colhidden = {}
              }
            }
          }
          excel.value.reloadConfig()
          let a = mapNumberToLetter(1);
          let b = mapNumberToLetter(99);
          excel.value.setRangeBgColor(0, `${a}${headerRow.value}:${b}${headerRow.value}`, '#f5f5f5')
          setTimeout(() => {
            getAllHeaderValues();
          }, 1000)
        }
      }
    );
  }
}

function getAllHeaderValues() {
  for (let i = 0; i < 99; i++) {
    let val = excel.value.getCellData(templateData.value.headerRow, i);
    if (val == null) {
      break;
    }
    headerValues.value.push({
      label: val,
      value: val
    });
  }
}

function exportExcel() {
  excel.value.exportExcel("模板设计.xlsx", 'office')
}

// function addItem() {
//   let cc = excel.value.getRange();
//   rowStartIndex = cc[0].row[0] + 1;
//   excel.value.addRow(rowStartIndex, rowStep);
//   let colorArr = ['#f5f5f5', '#effee3']
//   //遍历A-Z
//   for (let i = 0; i < 24; i++) {
//     if (i !== 3 && i !== 4) {
//       excel.value.setRangeMerge(0, 'vertical', `${arr[i]}${rowStartIndex}:${arr[i]}${rowStartIndex + rowStep}`);
//       // excel.value.setRangeBorder(0, `${arr[i]}${rowStartIndex}:${arr[i]}${rowStartIndex + rowStep}`)
//     }
//     excel.value.setRangeBgColor(0, `${arr[i]}${rowStartIndex}:${arr[i]}${rowStartIndex + rowStep}`, colorArr[a]);
//   }
//   rowStartIndex += rowStep + 1;
//   if (a === 0) {
//     a = 1
//   } else {
//     a = 0
//   }
// }

async function save() {
  const {error, data} = await fetchSaveTemplateBody({
    company: null,
    name: "",
    id: templateId.value,
    body: getData(),
    headerRow: headerRow.value,
  });
  if (!error) {
    message.success('保存成功');
    templateData.value = data
  }
}

function getData() {
  return excel.value.getSheetData();
}

function showRole() {
  showRoleModal.value = true
}

function showBaseConfig() {
  showBaseConfigModal.value = true
  getRowData(headerRow.value - 1, 100);
}

function onCreate() {
  return {
    name: '',
    columns: []
  }
}

async function submitSaveRole() {
  const {error} = await fetchSaveTemplateRole({
    company: null, name: "",
    id: templateId.value,
    role: roles.value
  });
  if (!error) {
    message.success('保存成功');
    showRoleModal.value = false
  } else {
    message.error(error.message);
  }
}

//基础配置
function getRowData(row: number, col: number) {
  let arr = [];
  for (let i = 0; i < col; i++) {
    let val = excel.value.getCellData(row, i);
    if (val != null) {
      // console.log(val)
      arr.push(val)
      let parameter = null;
      let symbol = mapNumberToLetter(i + 1);
      if (templateData.value.baseParameter) {
        for (let j = 0; j < templateData.value.baseParameter.length; j++) {
          let item = templateData.value.baseParameter[j];
          if (item.name === val) {
            parameter = item;
            item.symbol = symbol + "";
            break;
          }
        }
      }
      if (templateData.value.baseParameter == undefined) {
        templateData.value.baseParameter = [];
      }
      if (parameter == null) {
        templateData.value.baseParameter.push({
          index: i,
          symbol: symbol + "",
          name: val,
          inputMethod: '0',
          fixedValue: '',
          valueType: '0',
          regexp: '',
          formula: '',
          dynamicData: {
            h: [
              "", ""
            ],
            d: [["", ""]]
          }
        })
      }
    }
  }
  if (templateData.value.baseParameter) {
    for (let j = 0; j < templateData.value.baseParameter.length; j++) {
      let item = templateData.value.baseParameter[j];
      let flag = false;
      for (let i = 0; i < arr.length; i++) {
        let v = arr[i];
        if (item.name === v) {
          flag = true;
          break
        }
      }
      if (!flag) {
        //如果不存在则删除元素
        templateData.value.baseParameter.splice(j, 1)
      }
    }
  }
}

//保存基础配置
async function saveBaseParameter(e: MouseEvent) {
  e.preventDefault()
  const {error} = await fetchSaveTemplateBaseParameter({
    company: null,
    name: "",
    id: templateId.value,
    baseParameter: templateData.value.baseParameter
  });
  if (!error) {
    message.success('保存成功');
    showBaseConfigModal.value = false
  } else {
    message.error(error.message);
  }
  formRef.value?.validate((errors) => {
    if (!errors) {
      message.success('验证成功')
    } else {
      message.error('验证失败')
    }
  })
}

function addCol(index: number) {
  if (templateData.value.baseParameter) {
    templateData.value.baseParameter[index].dynamicData.h.push("");
    templateData.value.baseParameter[index].dynamicData.d.forEach((item: any) => {
      item.push("");
    })
  }
}

function addRow(index: number) {
  let arr: any = [];
  if (templateData.value.baseParameter) {
    templateData.value.baseParameter[index].dynamicData.h.forEach((item: any) => {
      arr.push("")
    })
    templateData.value.baseParameter[index].dynamicData.d.push(arr);
  }
}

function removeCol(index: number, index2: number) {
  if (templateData.value.baseParameter) {
    templateData.value.baseParameter[index2].dynamicData.h.splice(index, 1);
    templateData.value.baseParameter[index2].dynamicData.d.forEach((item: any) => {
      item.splice(index, 1)
    })
  }

}

function removeRow(index: number, index2: number) {
  if (templateData.value.baseParameter) {
    templateData.value.baseParameter[index2].dynamicData.d.splice(index, 1)
  }

}

function setShowCol(index: number, index2: number) {
  if (templateData.value.baseParameter) {
    templateData.value.baseParameter[index2].dynamicData.s = index;
  }
}

function setValCol(index: number, index2: number) {
  if (templateData.value.baseParameter) {
    templateData.value.baseParameter[index2].dynamicData.v = index;
  }
}

function headerRowUpdate(value: number) {
  let a = mapNumberToLetter(1);
  let b = mapNumberToLetter(99);
  excel.value.setRangeBgColor(0, `${a}${headerRow.value}:${b}${headerRow.value}`, '#ffffff')
  console.log('headerRowUpdate:', value, headerRow.value)
  excel.value.setRangeBgColor(0, `${a}${value}:${b}${value}`, '#f5f5f5')
}

onMounted(() => {
  getTemplate();
  window.addEventListener('keydown', handleEvent)
});

watch(() => showBaseConfigModal.value, (newVal) => {
  if (!newVal) {
  }
})
const handleEvent = async (event: any) => {
  if (event.keyCode == 83) {
    if (event.ctrlKey && event.code === 'KeyS') {
      event.preventDefault()
      event.returnValue = false
      await save();
    }
  }
}
</script>

<template>
  <n-space vertical style="padding-bottom: 0">
    <n-layout :style="{height: (innerHeight - 115) + 'px'}">
      <n-layout-header style="padding: 5px 5px 0;">
        <n-space style="gap: 5px 5px ">
          <n-input-number v-model:value="headerRow" max="100" min="1" size="small" @update-value="headerRowUpdate"
                          style="width: 120px">
            <template #prefix>
              表头:
            </template>
          </n-input-number>

          <!--          <n-button tertiary size="small" @click="cancel">-->
          <!--            关闭-->
          <!--          </n-button>-->
          <n-button tertiary size="small" type="primary" @click="save">
            保存
          </n-button>
          <n-button tertiary size="small" type="primary" @click="exportExcel">
            导出
          </n-button>
          <!--          <n-button tertiary size="small" type="primary" @click="addItem">-->
          <!--            添加订单项-->
          <!--          </n-button>-->
          <n-button tertiary size="small" type="primary" @click="showRole">
            权限配置
          </n-button>
          <n-button tertiary size="small" type="primary" @click="showBaseConfig">
            基础配置
          </n-button>
        </n-space>
      </n-layout-header>
      <n-layout-content :content-style="{height: (innerHeight - 150) + 'px',padding:'5px'}">
        <Excel ref="excel" :config="config"/>
      </n-layout-content>
      <n-layout-footer style="padding: 0;"></n-layout-footer>
    </n-layout>
    <n-modal v-model:show="showRoleModal">
      <n-card
        :style="{width:(width-200) + 'px'}"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
        content-style="padding:10px"
        footer-style="padding:10px;text-align:right"
      >
        <template #default>
          <n-dynamic-input :on-create="onCreate" v-model:value="roles" :round="false">
            <template #create-button-default>
              点击创建角色
            </template>
            <template #action="{ index,remove,create }">
              <n-space style="margin-left: 10px">
                <n-button-group size="small">
                  <n-button @click="() => remove(index)" size="small">
                    <n-icon>
                      <icon-material-symbols-delete-outline/>
                    </n-icon>
                  </n-button>
                  <n-button @click="() => create(index)" size="small">
                    <n-icon>
                      <icon-material-symbols-add-circle-outline/>
                    </n-icon>
                  </n-button>
                  <!--                  <n-button @click="() => create(index)" size="small">-->
                  <!--                    <n-icon>-->
                  <!--                      <icon-material-symbols-add-circle-outline/>-->
                  <!--                    </n-icon>-->
                  <!--                  </n-button>-->
                </n-button-group>

              </n-space>
            </template>
            <template #default="{ value }">
              <div style="display: flex; align-items: center; width: 100%">
                <n-input
                  size="small"
                  v-model:value="value.name"
                  style="margin-right: 12px; width: 160px"
                />
                <n-dynamic-tags v-model:value="value.columns" :style="{width: (width-500)+'px'}">
                  <template #input="{ submit, deactivate }">
                    <n-input @change="submit($event)" size="small" @blur="deactivate" placeholder="输入数据列名"></n-input>
                    <!--                    <n-auto-complete-->
                    <!--                      size="small"-->
                    <!--                      @select="submit($event)"-->
                    <!--                      @blur="deactivate"-->
                    <!--                      placeholder="输入数据列名"-->
                    <!--                      :input-props="{ autocomplete: 'disabled' }"-->
                    <!--                      :options="headerValues"-->
                    <!--                      clearable-->
                    <!--                    />-->
                  </template>
                </n-dynamic-tags>
              </div>
            </template>
          </n-dynamic-input>
        </template>
        <template #footer>
          <n-button type="info" size="small" @click="submitSaveRole">
            保存
          </n-button>
          <n-button size="small" style="margin-left: 10px" dashed @click="()=> showRoleModal = false">
            取消
          </n-button>
        </template>
      </n-card>
    </n-modal>
    <!--基本配置模态框-->
    <n-modal v-model:show="showBaseConfigModal">
      <n-card
        :style="{width:(width-200) + 'px'}"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
        content-style="padding:10px;height: 600px"
        footer-style="padding:10px;text-align:right"
      >
        <template #default>
          <n-tabs
            key="card_1"
            type="card"
            animated
            placement="top"
            tab-style="padding:5px 10px"
            :style="{height: '600px'}">
            <n-tab-pane v-for="(panel,indexb) in templateData.baseParameter" :key="indexb" :name="panel.name"
                        style="padding-top: 25px">
              <n-form
                :ref="'formRef'+panel.index"
                :model="panel"
                :rules="formRules"
                label-placement="left"
                label-width="auto"
                label-align="right"
                require-mark-placement="right-hanging"
                size="medium"
                :style="{maxWidth: '100%'}"
              >
                <n-form-item label="代表符号" path="symbol">
                  <n-input v-model:value="panel.symbol" placeholder="输入大写字母"/>
                </n-form-item>
                <n-form-item label="数据类型" path="inputMethod">
                  <n-radio-group v-model:value="panel.inputMethod" name="inputMethod">
                    <n-radio-button value="0">
                      常量
                    </n-radio-button>
                    <n-radio-button value="1">
                      单选
                    </n-radio-button>
                    <n-radio-button value="2">
                      输入
                    </n-radio-button>
                    <n-radio-button value="3">
                      公式
                    </n-radio-button>
                  </n-radio-group>
                </n-form-item>
                <n-form-item label="数据格式" path="valueType" v-show="panel.inputMethod==='2'">
                  <n-radio-group v-model:value="panel.valueType" name="valueType">
                    <n-radio-button value="0">
                      数字
                    </n-radio-button>
                    <n-radio-button value="1">
                      文本
                    </n-radio-button>
                    <n-radio-button value="2">
                      日期
                    </n-radio-button>
                    <n-radio-button value="3">
                      时间
                    </n-radio-button>
                    <n-radio-button value="4">
                      日期时间
                    </n-radio-button>
                    <n-radio-button value="5">
                      下拉框
                    </n-radio-button>
                    <n-radio-button value="6">
                      自定义
                    </n-radio-button>
                  </n-radio-group>
                </n-form-item>
                <n-form-item label="正则表达式" path="regexp" v-show="panel.valueType==='6' && panel.inputMethod == '2'">
                  <n-input v-model:value="panel.regexp" placeholder="输入正则表达式"/>
                </n-form-item>
                <n-form-item label="常量" path="fixedValue" v-show="panel.inputMethod==='0'">
                  <n-input v-model:value="panel.fixedValue" :placeholder="'输入【' + panel.name + '】的固定值'"/>
                </n-form-item>
                <n-form-item label="单选" path="fixedValue" v-show="panel.inputMethod==='1'">
                  <n-table :bordered="false" :single-line="false">
                    <thead>
                    <tr>
                      <template v-for="(s, index) in panel.dynamicData.h" :key="index">
                        <th style="padding: 3px;border: 1px solid #cecece;background-color: #bcbcbc">
                          <n-input type="text" size="small" placeholder="输入列名"
                                   v-model:value="panel.dynamicData.h[index]" style=""/>
                        </th>
                      </template>
                      <th style="padding: 3px;border: 0;background-color: #ffffff">
                        <!--添加行-->
                        <n-button quaternary type="info" size="small" @click="addCol(indexb)" style="float: left">
                          <template #icon>
                            <icon-material-symbols-add-circle-outline/>
                          </template>
                        </n-button>
                      </th>
                    </tr>
                    </thead>
                    <tbody>
                    <template v-for="(r, index1) in panel.dynamicData.d" :key="index1">
                      <tr>
                        <template v-for="(index2) in r" :key="index2">
                          <td style="padding: 3px;border: 1px solid #cecece">
                            <n-input type="text" size="small" placeholder="输入数值"
                                     v-model:value="panel.dynamicData.d[index1][index2]" style=""/>
                          </td>
                        </template>
                        <td style="padding: 3px;border:0">
                          <!--删除行-->
                          <n-button quaternary type="info" size="small" @click="removeRow(r,indexb)"
                                    style="float: left">
                            <template #icon>
                              <icon-material-symbols-delete-outline/>
                            </template>
                          </n-button>
                        </td>
                      </tr>
                    </template>
                    <tr>
                      <template v-for="(s,index) in panel.dynamicData.h" :key="index">
                        <td style="padding: 3px;border: 0;text-align: center">
                          <!--删除列-->
                          <n-button quaternary type="info" size="small" @click="removeCol(index,indexb)">
                            删除列
                          </n-button>
                          <n-checkbox size="small" label="展示列" @click="setShowCol(index,indexb)"
                                      :checked="panel.dynamicData.s == index"/>
                          <n-checkbox size="small" label="取值列" @click="setValCol(index,indexb)"
                                      :checked="panel.dynamicData.v == index"/>
                        </td>
                      </template>
                      <td style="padding: 3px;border: 0">
                        <!--添加行-->
                        <n-button quaternary type="info" size="small" @click="addRow(indexb)" style="float: left">
                          <template #icon>
                            <icon-material-symbols-add-circle-outline/>
                          </template>
                          添加行
                        </n-button>
                      </td>
                    </tr>
                    </tbody>
                  </n-table>
                </n-form-item>
                <n-form-item label="公式" path="formula" v-show="panel.inputMethod==='3'">
                  <n-input v-model:value="panel.formula" placeholder="输入公式"/>
                </n-form-item>

                <!--                <n-form-item label="Textarea" path="textareaValue">-->
                <!--                  <n-input-->
                <!--                    v-model:value="model.textareaValue"-->
                <!--                    placeholder="Textarea"-->
                <!--                    type="textarea"-->
                <!--                    :autosize="{ minRows: 3,maxRows: 5}"-->
                <!--                  />-->
                <!--                </n-form-item>-->
                <!--                <n-form-item label="Select" path="selectValue">-->
                <!--                  <n-select-->
                <!--                    v-model:value="model.selectValue"-->
                <!--                    placeholder="Select"-->
                <!--                    :options="generalOptions"-->
                <!--                  />-->
                <!--                </n-form-item>-->
                <!--                <n-form-item label="Multiple Select" path="multipleSelectValue">-->
                <!--                  <n-select-->
                <!--                    v-model:value="model.multipleSelectValue"-->
                <!--                    placeholder="Select"-->
                <!--                    :options="generalOptions"-->
                <!--                    multiple-->
                <!--                  />-->
                <!--                </n-form-item>-->
                <!--                <n-form-item label="Datetime" path="datetimeValue">-->
                <!--                  <n-date-picker v-model:value="model.datetimeValue" type="datetime"/>-->
                <!--                </n-form-item>-->
                <!--                <n-form-item label="Switch" path="switchValue">-->
                <!--                  <n-switch v-model:value="model.switchValue"/>-->
                <!--                </n-form-item>-->
                <!--                <n-form-item label="Checkbox Group" path="checkboxGroupValue">-->
                <!--                  <n-checkbox-group v-model:value="model.checkboxGroupValue">-->
                <!--                    <n-space>-->
                <!--                      <n-checkbox value="Option 1">-->
                <!--                        Option 1-->
                <!--                      </n-checkbox>-->
                <!--                      <n-checkbox value="Option 2">-->
                <!--                        Option 2-->
                <!--                      </n-checkbox>-->
                <!--                      <n-checkbox value="Option 3">-->
                <!--                        Option 3-->
                <!--                      </n-checkbox>-->
                <!--                    </n-space>-->
                <!--                  </n-checkbox-group>-->
                <!--                </n-form-item>-->
                <!--                <n-form-item label="Radio Group" path="radioGroupValue">-->
                <!--                  <n-radio-group v-model:value="model.radioGroupValue" name="radiogroup1">-->
                <!--                    <n-space>-->
                <!--                      <n-radio value="Radio 1">-->
                <!--                        Radio 1-->
                <!--                      </n-radio>-->
                <!--                      <n-radio value="Radio 2">-->
                <!--                        Radio 2-->
                <!--                      </n-radio>-->
                <!--                      <n-radio value="Radio 3">-->
                <!--                        Radio 3-->
                <!--                      </n-radio>-->
                <!--                    </n-space>-->
                <!--                  </n-radio-group>-->
                <!--                </n-form-item>-->

              </n-form>
            </n-tab-pane>
          </n-tabs>
        </template>
        <template #footer>
          <n-button type="info" size="small" @click="saveBaseParameter">
            保存
          </n-button>
          <n-button size="small" style="margin-left: 10px" dashed @click="()=> showBaseConfigModal = false">
            取消
          </n-button>
        </template>
      </n-card>
    </n-modal>
  </n-space>

</template>

<style scoped>

</style>
